<template>
  <div>
    <Header />
    <div class="search-container">
      <!-- 搜索框 -->
      <div class="search-box">
        <div class="search-input-wrapper">
          <input type="text" class="search-input" placeholder="请输入景点名称" v-model="searchQuery">
          <span class="clear-button" v-show="searchQuery" @click="clearSearch">×</span>
        </div>
        <button class="search-btn" @click="search">搜索</button>
      </div>

      <div class="search-content">
        <!-- 筛选条件 -->
        <div class="search-filters">
          <div class="filter-row">
            <span class="filter-label">国家:</span>
            <div class="filter-options">
              <span class="filter-option" 
                    v-for="country in countries" 
                    :key="country"
                    :class="{ active: selectedCountry === country }"
                    @click="selectedCountry = selectedCountry === country ? '' : country">{{ country }}</span>
            </div>
          </div>

          <div class="filter-row">
            <span class="filter-label">省份:</span>
            <div class="filter-options" :class="{ 'is-loading': isProvincesLoading }">
              <span v-if="!selectedCountry" class="filter-prompt">请先选择国家</span>
              <template v-else>
                <span class="filter-option" v-for="province in provinces" :key="province"
                      :class="{ active: selectedProvince === province }"
                      @click="selectedProvince = selectedProvince === province ? '' : province">{{ province }}</span>
              </template>
            </div>
          </div>

          <div class="filter-row">
            <span class="filter-label">分类:</span>
            <div class="filter-options">
              <span class="filter-option" v-for="category in categories" :key="category"
                    :class="{ active: selectedCategory === category }"
                    @click="selectedCategory = selectedCategory === category ? '' : category">{{ category }}</span>
            </div>
          </div>
        </div>

        <!-- 搜索结果 -->
        <div class="search-results">
          <!-- 无数据提示 -->
          <div class="no-data" v-if="scenicSpots.length === 0">
            <span class="no-data-text">当前地区暂未开放景区</span>
          </div>
          <!-- 景点列表 -->
          <div class="result-item" v-else v-for="spot in scenicSpots" :key="spot.id">
            <div class="spot-image">
              <img 
                :src="getImagePath(spot.mainCoverImage)" 
                :alt="spot.name"
                @error="handleImageError"
              >
            </div>
            <div class="spot-info">
              <div class="spot-name">
                <h3 v-html="spot.name"></h3>
                <span class="spot-category" v-html="spot.category"></span>
              </div>
              <div class="spot-address">
                <span v-html="spot.province"></span>
                {{ spot.address }}
              </div>
              <div class="spot-features">
                <span class="feature" v-for="(feature, index) in spot.features" :key="index">
                  {{ feature }}
                </span>
              </div>
              <div class="spot-bottom">
                <div class="spot-rating">
                  <span class="rating">{{ spot.rating }}/5分</span>
                </div>
                <button class="detail-btn" @click.stop="goToDetail(spot.attractionId)">查看详情</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="total > 0">
          <button :disabled="pageNum <= 1" @click="changePage(pageNum - 1)">&lt; 上一页</button>
          <span>{{ pageNum }} / {{ Math.ceil(total / pageSize) }}</span>
          <button :disabled="pageNum >= Math.ceil(total / pageSize)" @click="changePage(pageNum + 1)">下一页 &gt;</button>
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script>
import Header from './Header.vue'
import Footer from './Footer.vue'
import axios from 'axios'

export default {
  name: 'Search',
  components: {
    Header,
    Footer
  },
  data() {
    return {
      searchQuery: '',
      selectedCountry: '',
      selectedProvince: '',
      selectedCategory: '',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      defaultImage: new URL('../imgs/abc.jpg', import.meta.url).href,
      // 扩展国家数据
      countries: ['中国', '日本', '韩国', '泰国', '新加坡', '马来西亚', '越南', '印度尼西亚', '美国', '法国'],
      provinces: [],
      // 各国省份/地区数据
      provinceMap: {
        '中国': ['上海', '北京', '广东', '浙江', '江苏', '四川', '云南', '海南', '湖北', '湖南', '河北', '河南', '山东', '山西', '陕西', '福建', '江西', '安徽', '贵州', '广西', '青海', '甘肃', '辽宁', '吉林', '黑龙江', '内蒙古', '西藏', '新疆', '宁夏', '澳门', '香港'],
        '日本': ['东京都', '大阪府', '京都府', '冲绳县', '北海道', '福冈县', '神奈川县', '爱知县', '兵库县', '千叶县'],
        '韩国': ['首尔特别市', '釜山广域市', '济州特别自治道', '仁川广域市', '大邱广域市', '光州广域市', '大田广域市', '蔚山广域市'],
        '泰国': ['曼谷', '普吉府', '清迈府', '春武里府', '甲米府', '素叻他尼府', '清莱府', '沙没巴干府'],
        '新加坡': ['中央商务区', '乌节路', '克拉码头', '圣淘沙岛', '马里那湾', '小印度', '牛车水', '东海岸'],
        '马来西亚': ['吉隆坡', '槟城', '马六甲', '沙巴', '砂拉越', '柔佛', '霹雳', '登嘉楼'],
        '越南': ['河内市', '胡志明市', '岘港市', '芽庄市', '顺化市', '会安市', '大叻市', '美奈市'],
        '印度尼西亚': ['巴厘岛', '雅加达', '日惹特区', '龙目岛', '泗水', '万隆', '棉兰', '马卡萨'],
        '美国': ['纽约州', '加利福尼亚州', '佛罗里达州', '德克萨斯州', '内华达州', '夏威夷州', '华盛顿州', '马萨诸塞州', '伊利诺伊州', '亚利桑那州', '科罗拉多州', '俄勒冈州', '阿拉斯加州'],
        '法国': ['法兰西岛大区', '普罗旺斯-阿尔卑斯-蓝色海岸大区', '奥克西塔尼大区', '新阿基坦大区', '布列塔尼大区', '上法兰西大区', '诺曼底大区', '大东部大区', '卢瓦尔河谷大区', '勃艮第-弗朗什孔泰大区']
      },
      categories: ['自然风景', '历史古迹', '主题乐园', '美食之都', '文化遗产', '公园游览', '海滩度假', '博物馆', '地标建筑', '登山徒步', '购物天堂'],
      scenicSpots: [],
      isProvincesLoading: false // 新增加载状态
    }
  },
  watch: {
    // 监听国家选择的变化
    selectedCountry: {
      handler(newCountry) {
        if (newCountry) {
          this.updateProvinces(newCountry);
        } else {
          this.provinces = [];  // 当国家为空时，清空省份列表
        }
        // 切换国家时清空已选省份
        this.selectedProvince = '';
        // 重置页码
        this.pageNum = 1;
        // 重新搜索
        this.search();
      },
      immediate: true
    },
    // 监听省份选择的变化
    selectedProvince: {
      handler() {
        this.pageNum = 1;
        this.search();
      }
    },
    // 监听分类选择的变化
    selectedCategory: {
      handler() {
        this.pageNum = 1;
        this.search();
      }
    },
    // 监听搜索关键词的变化
    searchQuery: {
      handler() {
        this.pageNum = 1;
        this.search();
      }
    }
  },
  created() {
    // 从路由参数中获取搜索参数
    const { province, category, keyword, searchType } = this.$route.query;
    
    // 设置搜索栏的值（使用第一个不为空的参数）
    this.searchQuery = province || category || keyword || '';
    
    // 根据搜索类型设置相应的参数
    if (searchType === 'region' && province) {
      this.selectedProvince = province;
    } else if (searchType === 'category' && category) {
      this.selectedCategory = category;
    }
    
    // 执行搜索
    this.search();
  },
  methods: {
    clearSearch() {
      this.searchQuery = '';
      this.search(); // 清空后重新搜索
    },
    // 更新省份列表
    async updateProvinces(country) {
      this.isProvincesLoading = true; // 开始加载
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 300));
        
        // 获取对应国家的省份数据
        const provinces = this.provinceMap[country] || [];
        this.provinces = provinces;
        
      } catch (error) {
        console.error('获取省份数据失败:', error);
        this.provinces = [];
      } finally {
        this.isProvincesLoading = false; // 结束加载
      }
    },
    async search() {
      try {
        const response = await axios.post('/scenicspot/searchByRegionAndCategory', {
          keyword: this.searchQuery,
          country: this.selectedCountry,
          province: this.selectedProvince,
          category: this.selectedCategory,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        });
        
        if (response.code === 200) {
          const { data, total, pageNum } = response.data;
          this.scenicSpots = data;
          this.total = total;
          this.pageNum = pageNum;
        }
      } catch (error) {
        console.error('搜索失败:', error);
      }
    },
    changePage(page) {
      this.pageNum = page
      this.search()
    },
    goToDetail(spotId) {
      this.$router.push(`/scenic/attractionId=${spotId}`);
    },
    // 处理图片路径
    getImagePath(filename) {
      console.log('处理图片路径:', filename);
      if (!filename) {
        console.log('文件名为空，使用默认图片');
        return this.defaultImage;
      }

      // 检查是否是在线URL
      if (filename.startsWith('http://') || filename.startsWith('https://')) {
        console.log('使用在线图片路径:', filename);
        return filename;
      }

      // 处理本地图片路径
      try {
        return new URL(`../imgs/${filename}`, import.meta.url).href;
      } catch (error) {
        console.error('图片路径生成失败:', error);
        return this.defaultImage;
      }
    },

    // 处理图片加载失败
    handleImageError(event) {
      console.log('图片加载失败，原始src:', event.target.src);
      console.log('切换到默认图片');
      event.target.src = this.defaultImage;
    }
  },
  mounted() {
    this.search()
  }
}
</script>

<style scoped>
.search-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.search-box {
  max-width: 1200px;
  margin: 0 auto 20px;
  display: flex;
  gap: 10px;
}

.search-input-wrapper {
  position: relative;
  flex: 1;
  display: flex;
  align-items: center;
}

.search-input {
  width: 100%;
  padding: 10px 35px 10px 15px; /* 增加右边距给清除按钮留空间 */
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.search-input:hover {
  border-color: #1890ff;
}

.search-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  outline: none;
}

.clear-button {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  border-radius: 50%;
  color: #999;
  cursor: pointer;
  font-size: 18px;
  background-color: rgba(0, 0, 0, 0.1);
  opacity: 0;
  transition: all 0.3s;
}

.search-input-wrapper:hover .clear-button {
  opacity: 0.6;
}

.clear-button:hover {
  opacity: 1 !important;
  background-color: rgba(0, 0, 0, 0.2);
  color: #666;
}

.search-btn {
  padding: 0 30px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-content {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.search-filters {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.filter-label {
  width: 80px;
  color: #666;
  flex-shrink: 0;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  position: relative;
  min-height: 32px;
}

.filter-options.is-loading::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
}

.filter-options.is-loading::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20px;
  height: 20px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  z-index: 1;
}

@keyframes spin {
  0% { transform: translate(-50%, -50%) rotate(0deg); }
  100% { transform: translate(-50%, -50%) rotate(360deg); }
}

.filter-option {
  padding: 5px 15px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.filter-option:hover {
  color: #1890ff;
}

.filter-option.active {
  background: #e6f7ff;
  color: #1890ff;
}

.filter-prompt {
  color: #999;
  font-style: italic;
  padding: 5px 15px;
}

.result-item {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s;
}

.result-item:hover {
  background: #fafafa;
}

.spot-image {
  width: 280px;
  height: 180px;
  margin-right: 20px;
  flex-shrink: 0;
}

.spot-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.spot-info {
  flex: 1;
}

.spot-name {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.spot-name h3 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.spot-category {
  padding: 2px 8px;
  background: #f0f0f0;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.spot-address {
  color: #666;
  margin-bottom: 10px;
}

.spot-features {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.feature {
  padding: 2px 8px;
  background: #f5f5f5;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.spot-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.spot-rating {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rating {
  color: #ff6600;
  font-weight: bold;
}

.reviews {
  color: #999;
  font-size: 12px;
}

.spot-price {
  display: none;
}

.book-btn {
  margin-left: auto;
  padding: 8px 20px;
  background: #ff6600;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.book-btn:hover {
  background: #ff8533;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
  padding: 20px 0;
}

.pagination button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.pagination button:not(:disabled):hover {
  border-color: #1890ff;
  color: #1890ff;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  width: 100%;
}

.no-data-text {
  font-size: 28px;
  color: rgba(0, 0, 0, 0.15);
  font-weight: bold;
}

.detail-btn {
  padding: 6px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.detail-btn:hover {
  background: #40a9ff;
}

.detail-btn:active {
  background: #096dd9;
}
</style> 